package com.sopaths.crawler.zhilian;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;

import javax.inject.Named;

import org.apache.http.client.utils.URIBuilder;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.sopaths.contract.crawler.RecruitmentSummary;
import com.sopaths.crawler.SummaryCrawler;
import com.sopaths.crawler.tasks.SummaryCrawlerTask;

@Named
public class ZhiLianSummaryCrawler extends SummaryCrawler {

	private Logger logger = Logger.getLogger(ZhiLianSummaryCrawler.class);

	@Override
	protected String assembleSummaryUrl(SummaryCrawlerTask task) {
		try {
			URI uri = new URIBuilder().setScheme("http")
					.setHost("sou.zhaopin.com")
					.setPath("/Jobs/searchresult.ashx")
					.setParameter("jl", task.getCity().getName())
					.setParameter("sm", "0")
					.setParameter("p", task.getPage() + "")
					.setParameter("sf", "0").build();
			return uri.toString();
		} catch (URISyntaxException ex) {
			logger.error("An error occurred while assembling URL.", ex);
			throw new RuntimeException(ex);
		}
	}

	@Override
	protected void assembleSummaryTaskResult(SummaryCrawlerTask task, Document document) {
		List<RecruitmentSummary> summaries = new LinkedList<>();
		Elements elements = document.select(".JobName a");
		for (Element element : elements) {
			String href = element.attr("href");
			RecruitmentSummary summary = new RecruitmentSummary();
			summary.setUrl(href);
			summaries.add(summary);
		}
		task.setResult(summaries);
	}
/*
	@Override
	public void crawl(CrawlerTask<?> task) {
		try {
			SummaryCrawlerTask innerTask = (SummaryCrawlerTask) task;

			URI uri = new URIBuilder().setScheme("http")
					.setHost("sou.zhaopin.com")
					.setPath("/Jobs/searchresult.ashx")
					.setParameter("jl", URLEncoder.encode(innerTask.getCity().getName(), "ISO-8859-1"))
					.setParameter("sm", "0")
					.setParameter("p", innerTask.getPage() + "")
					.setParameter("sf", "0").build();
			HttpGet httpGet = new HttpGet(uri);
			try (CloseableHttpResponse response = getHttpClient().execute(httpGet)) {
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
				Document document = Jsoup.parse(html);
				List<RecruitmentSummary> summaries = new LinkedList<>();
				Elements elements = document.select(".JobName a");
				for (Element element : elements) {
					String href = element.attr("href");
					RecruitmentSummary summary = new RecruitmentSummary();
					summary.setUrl(href);
					summaries.add(summary);
				}
				innerTask.setResult(summaries);
			}
		} catch (Exception ex) {
			logger.error("An error occurred while crawling.", ex);
		}
	}
*/
}
